package com.tiger.cloud.controller.crm;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Timestamp;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.tiger.cloud.common.mybatis.BaseController;
import com.tiger.cloud.filter.IgnoreAuth;
import com.tiger.cloud.model.crm.AppVersion;
import com.tiger.cloud.model.ext.AppVersionRequest;
import com.tiger.cloud.service.crm.IAppVersionService;
import com.tiger.cloud.util.ErrorCode;
import com.tiger.cloud.util.FileUploadService;
import com.tiger.cloud.util.Response;
import com.tiger.cloud.util.ResponseUtil;
import com.tiger.cloud.util.UploadApkFileUtil;

/**
 * app版本控制
 */
@Controller
@RequestMapping(value = "appVersion")
@Api(value = "APP版本", tags = "版本")
public class AppVersionController extends BaseController {

    @Autowired
    private IAppVersionService appVersionService;
    @Autowired
    private FileUploadService fileUploadService;

    /**
     * 查找最新版本的APP
     */
    @RequestMapping(value = "findNewVersion", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "查找最新版本的APP", notes = "")
    @IgnoreAuth
    public Response findNewVersion(@ApiParam(name = "client", value = "客户端：0：安卓,1：IOS", required = true) @RequestBody Integer client) {
        AppVersion appVersion = new AppVersion();
        appVersion.setClient(client);
        appVersion.setStartUseTime(new Timestamp(System.currentTimeMillis()));
        //appVersion.setOrderBy("APP_VERSION.start_use_time desc");
        appVersion.setPageIndex(0);
        appVersion.setPageSize(1);
        AppVersion datas = appVersionService.findNewVersion(appVersion);
        return ResponseUtil.ok(datas);
    }
    
    /**
     * 查找最新版本的APP
     */
    @RequestMapping(value = "findNewVersion2", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "查找最新版本的APP", notes = "")
    @IgnoreAuth
    public Response findNewVersion2(@ApiParam(name = "client", value = "客户端：0：安卓,1：IOS", required = true) @RequestBody AppVersionRequest versionRequest) {
    	if(versionRequest.getClient()==null||versionRequest.getClient()!=1){
    		versionRequest.setClient(1);
    	}
        AppVersion appVersion = new AppVersion();
        appVersion.setClient(versionRequest.getClient());
        appVersion.setStartUseTime(new Timestamp(System.currentTimeMillis()));
        appVersion.setPageIndex(0);
        appVersion.setPageSize(1);
        AppVersion datas = appVersionService.findNewVersion(appVersion);
        return ResponseUtil.ok(datas);
    }

    //	/**
//	 * APK文件下载
//	 * @param request
//	 * @param response
//	 * @param filename
//	 * @throws IOException
//	 */
//	@RequestMapping(value = "/down/android/{filename}", method = RequestMethod.GET)
//	@ApiOperation(value = "下载apk文件",notes = "")
//	@IgnoreAuth
//	public void downloadApp(HttpServletRequest request, HttpServletResponse response, @PathVariable("filename") String filename) throws IOException {
//		Boolean targetDownload = null;
//		File apkFile = new File("/opt/apps/android");
//		String[] filenames = apkFile.list();
//		if (StringUtils.isNotEmpty(filename) && filenames != null) {
//			filename = filename + ".apk";
//			for (String apkFilename : filenames) {
//				if (apkFilename.equals(filename)) {
//					targetDownload = true;
//				}
//			}
//		}
//		if (targetDownload != null) {
//			File downloadFile = new File(apkFile, filename);
//			try {
//				response.setContentType("application/vnd.android.package-archive");
//				response.setHeader("Content-Length", String.valueOf(downloadFile.length()));
//				response.setHeader("content-transfer-encoding", "binary");
//				response.setHeader("Content-Disposition", "attachment; filename=" + filename);
//				OutputStream outputStream = response.getOutputStream();
//				outputStream.write(FileUtils.readFileToByteArray(downloadFile));
//				outputStream.close();
//			} catch (FileNotFoundException e1) {
//				e1.printStackTrace();
//			} catch (Exception e) {
//				e.printStackTrace();
//			}
//		}else{
//			ServletUtil.writeJson("你很笨,( ^___^ ) (*^﹏^*) ( ^_^ ) ( *^_^* ) (*^__^*) ^_^ o(∩_∩)o ~^o^~ (^-^) (^o^) └(^o^)┘ ^v^ ", response);
//		}
//	}
    @RequestMapping(value = "uploadApkFile", method = RequestMethod.POST)
    @ResponseBody
    @CrossOrigin
    @IgnoreAuth
    public Response uploadApkFile(@RequestParam(value = "file") MultipartFile file) throws IOException {
        if(file == null){
            return ResponseUtil.error();
        }
        InputStream inputStream = file.getInputStream();
       
        try {
            String fileName = UploadApkFileUtil.uploadApk(inputStream,file.getOriginalFilename());
            if(!StringUtils.isEmpty(fileName)){
                return ResponseUtil.ok(fileName);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseUtil.error();
        }
        return ResponseUtil.error();
    }

    @RequestMapping("uploadImage")
    @ResponseBody
    @CrossOrigin
    public Response uploadImage(MultipartFile imageFile, HttpServletRequest request, HttpServletResponse response) {
        try {
            String[] string = fileUploadService.upload(request, imageFile, FileUploadService.IMAGE_EXTENSION);
            return ResponseUtil.ok(string[1]);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResponseUtil.error(ErrorCode.INTERNAL_ERROR);
    }
}